<?php

namespace app\admin\controller\shop;

use app\common\controller\Backend;

use app\common\model\Order;
use think\Controller;
use think\Request;

/**
 * 订单
 *
 * @icon fa fa-circle-o
 */
class Shoporder extends Backend
{
    
    /**
     * ShopOrder模型对象
     */
    protected $model = null;
    protected $shopOrderItem = null;
    protected $searchFields = 'order_no';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('ShopOrder');
        $this->shopOrderItem = model('ShopOrderItem');
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->assignconfig('statusList', $this->model->getStatusList());

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个方法
     * 因此在当前控制器中可不用编写增删改查的代码,如果需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 子商品详情
     */
    public function detail($ids = '')
    {
        $order = $this->model->get($ids);
        if (!$order)
            $this->error(__('The Order is no found'));
        //退款请求
        if ($this->request->isAjax()) {
            $orderItem = $this->shopOrderItem
                ->where(['id' => input('item_id')])
                ->with('order')
                ->find();
            if($orderItem->is_refund == 1)
                $this->error(__('The goods have been refunded'));
            $orderNo = $orderItem->order->order_no;
            $refundNo = $orderNo.'_'.$orderItem->id;
            $refundFee = $orderItem->item_price;


            $wechatApp = new \app\mpbase\library\WechatApp();
            $result = $wechatApp->refund($orderNo,$refundNo,$refundFee);
//            $result = action('mpbase/WechatApp/refund',
//                    ['orderNo'=>$orderNo,'refundNo'=>$refundNo,'refundFee'=>$refundFee]);
            if($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
                $orderItem->refund_no = $refundNo;
                $orderItem->refund_id = $result->refund_id;
                $orderItem->is_refund = 1;
                $orderItem->save();
                $this->success();
            }

            $this->error($orderItem->getError());


        }
        $row = $this->shopOrderItem->where(['order_id' => $ids])->select();
        if (!$row)
            $this->error(__('No Results were found'));
        $this->view->assign("order", $order);
        $this->view->assign("row", $row->toArray());
        return $this->view->fetch();
    }

    /**
     * 发货
     */
    public function send($ids)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds))
        {
            if (!in_array($row[$this->dataLimitField], $adminIds))
            {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()){
            $params = $this->request->post("row/a");
            if ($params)
            {
                try
                {
                    //是否采用模型验证
                    if ($this->modelValidate)
                    {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false)
                    {
                        return $this->success();
                    }
                    else
                    {
                        $this->error($row->getError());
                    }
                }
                catch (\think\exception\PDOException $e)
                {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $row = $this->model->get($ids);
        $row['shipping_time'] == 0 && $row['shipping_time'] = time();
        $this->view->assign("row", $row->toArray());
        return $this->view->fetch();
    }


    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids)
        {
            $adminIds = explode(',',$ids);
            $count = $this->model
                ->where('status','neq',Order::ORDER_WAIT_PAY)
                ->where('id', 'in', $adminIds)
                ->count();
            if($count>0)
            {
                $this->error(__('Paid order do not delete'));
            }

            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            $list = $this->model->where($pk, 'in', $ids)->select();
            $count = 0;
            foreach ($list as $k => $v)
            {
                $count += $v->delete();
                $this->shopOrderItem
                    ->where('order_id',$v['id'])
                    ->delete();
            }
            if ($count)
            {
                $this->success();
            }
            else
            {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
}
